/**
 * 报事
 * @author levy
 * @date    2016/1/10
 * @signForription []
 */
import TextArea from "../components/form/TextArea.js";

(function (lf, r) {
    var ajax = lf.utils.ajax,
        doAction = lf.bridgeJs.doAction,
        pics = [], //唉,全局变量是魔鬼啊
        env = lf.utils.getEnv(),
        systemFlag = lf.utils.getSys(),
        flag = lf.utils.getUrlParam('flag');

    const FINGER = 'finger';

    var SelectProject = r.createClass({
        getInitialState: function () {
            return {
                optionList: [],
                hasLoaded: false,
            };
        },
        componentDidUpdate: function (preProps, prevState) {
            var me = this;

            if (!me.state.hasLoaded) {
                ajax({
                    data: {
                        staffId: this.props.user.id,
                    },
                    success: function (data) {
                        var optionList = data.dataList.map(function (data) {
                            return <option value={data.id}>{data.fullName}</option>
                        });

                        me.setState({
                            optionList: optionList,
                            hasLoaded: true,
                        })
                    }
                }, lf.api.projectList);
            }
        },
        render: function () {
            return (
                <div className="select-project">
                    <p className="text-title">选择项目</p>
                    <select name="projectId" id="projectId"
                            className={env == 'app' && systemFlag == 'IOS' ? 'ios' : ''}>
                        {this.state.optionList}
                    </select>
                </div>
            );
        }
    });

    var Img = r.createClass({
        delFn: function (e) {
            this.props.deleteItem(e);
        },
        render: function () {
            return (
                <div className="item ele-hide">
                    <img className="photo"/>
                    <a onTouchEnd={this.delFn} data-type="deleteBtn" className="delete-btn">
                        <span className="delete-icon"/>
                    </a>
                </div>
            );
        }
    });

    var Imgs = React.createClass({
        getInitialState: function () {
            return ({});
        },
        deleteItem: function (e) {
            //alert('deleteItem');
            var $item;
            //点击的是a元素
            if (e.target.getAttribute('data-type') == 'deleteBtn') {
                $item = $(e.target).parent();
            } else {
                //由于事件捕获,可能点击的是span
                $item = $(e.target).parent().parent();
            }
            $item.toggleClass('ele-hide');

            //数据修改
            var $img = $item.find('img');
            var $imgList = $('img[src]');
            //alert(pics.toString());
            for (var i = 0; i < $imgList.length; i++) {
                if ($img[0] == $imgList[i]) {
                    $img.attr('src', null);
                    //修改数组,这个是要提交到后台的数据
                    pics.splice(i, 1);
                    break;
                }
            }
            $('.up-load').show();
        },
        render: function () {
            var count = [1, 2, 3, 4, 5, 6, 7, 8, 9];
            var me = this;
            var itemList = count.map(function () {
                return <Img deleteItem={me.deleteItem}/>;
            });
            //log(itemList)
            return (
                <div className="box flex-box-row">
                    {itemList}
                    <a className="up-load btn item">
                        <span ref="addBtn"/>
                    </a>
                </div>
            );
        },
        componentDidMount: function () {
            r.findDOMNode(this.refs.addBtn).addEventListener('tap', (e) => {
                if (this.props.isTextSelected)
                    lf.utils.slideDownKeyboard(() => {
                        lf.bridgeJs.selectPhoto(9 - pics.length);
                    });
                else
                    lf.bridgeJs.selectPhoto(9 - pics.length);
            });
        },

    });

    //指点报事要用到
    let ajaxData = {
        houseNum: '',
        proprietorName: '',
    };

    //这里决定放几个Imgs
    var Report = React.createClass({
        getInitialState: function () {
            return {
                user: '',
                location: '',
                isTextSelected: false,
            }
        },
        componentWillMount: function () {
            let me = this;
            lf.bridgeJs.getUser(function (user) {
                me.setState({
                    user: user,
                });

                if (flag == FINGER) {
                    if (user.houseId)
                        ajax({
                            data: {
                                houseId: user.houseId,
                            }
                        }, lf.finger.api.household.getHouseInfo, function (data) {
                            ajaxData.houseNum = data.houseNum;
                            ajaxData.proprietorName = data.proprietorName;
                            me.setState({location: data.houseNum});
                        });
                }
            }.bind(this));
        },
        componentDidMount: function () {
            var me = this;

            r.findDOMNode(this.refs.btn).addEventListener('tap', function () {
                me.submit();
            });

            r.findDOMNode(this.refs.toReportList).addEventListener('tap', function () {

                if (flag == FINGER) {
                    doAction('report-history-list.html?flag=' + flag, '报事列表')
                } else {
                    doAction('report-history-list.html?flag=', '报事列表')
                }

            })
        },
        //处理文本框函数
        focusFn() {
            this.setState({isTextSelected: true});
        },
        blurFn() {
            this.setState({isTextSelected: false});
        },
        submit: function (e) {
            var location = $('#worklocation').val();
            var content = $('#content').val();
            //alert(user.loginid)

            if (!location) {
                mui.toast('事件位置不能为空');
                return false;
            }
            if (!content) {
                mui.toast('内容描述不能为空');
                return false;
            }

            if (location.length > 40) {
                mui.toast('事件位置的字数不能超过40个');
                return false;
            }
            if (content.length > 250) {
                mui.toast('内容描述的字数不能超过250个');
                return false;
            }

            var me = this,
                user = liefeng.userInfo,
                count = $('img[src]').length,
                api = flag == FINGER ? lf.finger.api.event.create : lf.api.report.create;

            //兼容 debug
            if (!flag && count || lf.utils.getEnv() == 'pc' || flag == FINGER) {
                //兼容指点及调试
                let $project = $('#projectId'),
                    projectId = $project && $project.val() || user.projectId;

                lf.bridgeJs.doLoading(true);

                var $btn = $('button'),
                    createReport = function (pics) {
                        // debugAlert('创建报事');
                        ajax({
                            async: false,
                            type: 'post',
                            contentType: 'application/x-www-form-urlencoded; charset=GBK',//utf-8
                            data: {
                                staffId: user.id,
                                projectId: projectId,
                                location: location,
                                content: content,
                                phone: user.phone || user.mobile,
                                picUrl: pics,
                                reporterName: user.name,
                                houseNum: ajaxData.houseNum,
                                proprietorName: ajaxData.proprietorName,
                            },
                            success: function (data) {
                                lf.bridgeJs.doLoading(false);

                                if (data.code == '200') {
                                    mui.toast('报事成功');
                                    setTimeout(function () {
                                        window.location.reload();
                                    }, 200);
                                } else {
                                    mui.toast(data.desc);
                                }
                            },

                        }, api);
                    };
                $btn.toggleClass('ele-hide').next().toggleClass('ele-hide');
                lf.bridgeJs.uploadImg(pics.toString(), createReport);

            } else {
                mui.toast('必须上传图片');
            }
        },
        //父组件传data给子组件
        render: function () {
            return (
                <div className="report">
                    <div name="form" action="#">
                        {flag == FINGER ? '' : <SelectProject user={this.state.user}/>}
                        <div>
                            <p className="text-title">事件位置</p>
                            <TextArea name="worklocation" placeholder="请输入事件具体位置" value={this.state.location}
                                      focusFn={this.focusFn} blurFn={this.blurFn}/>
                        </div>
                        <div>
                            <p className="text-title">内容描述</p>
                            <TextArea name="content" placeholder="请输入需要报事的内容描述"
                                      focusFn={this.focusFn} blurFn={this.blurFn}/>
                        </div>
                        <Imgs ref="Imgs" isTextSelected={this.state.isTextSelected}/>
                        <button
                            style={flag == FINGER ? {backgroundColor: '#28b6c2', borderColor: '#28b6c2'} : {borderColor: '#2cc57b'}}
                            ref="btn" className="mui-btn lf-green-btn form-submit-btn confirm-btn">确认提交
                        </button>
                        <input type="button" value="确认提交" className="mui-btn form-submit-btn ele-hide"
                               disabled="disabled"/>
                        <a href="javascript:;"
                           className={"mui-btn form-submit-btn to-history " + ( flag == FINGER ? 'finger-history' : 'oa-history' )}
                           ref="toReportList">历史报事
                        </a>
                    </div>
                </div>
            );

        },
    });

    r.render(
        <Report />,
        document.getElementById('root'),
        function () {
            //deprecated 以后不要这样写,具体看bridge4app.js注释
            lf.bridgeJs.connectBridge2RegisterHandler(function (bridge) {

                //返回的是手机才能识别的图片地址
                bridge.registerHandler("getPhotoFromApp", function (data, cb) {
                    //alert("getPhotoFromApp = " + data);

                    var srcs = data.split(','),
                        len = srcs.length,
                        $itemList = $('.item'),
                        count = $('img[src]').length,//已有的图片个数
                        $upLoad = $('.up-load');

                    for (var i = 0; i < len; i++) {
                        var $item = $itemList.eq(i + count);
                        //隐藏父元素就可以啦!
                        $item.toggleClass('ele-hide')
                            .children().attr('src', srcs[i]);

                        pics.push(srcs[i]);//上传图片时要用到
                    }

                    if (count + len >= 9)
                        $upLoad.hide();
                });
            })
        }
    )

})(liefeng, React);
